package cn.sala.user.controller;

import cn.sala.distributedlock.redis.RedissLockUtil;
import cn.sala.user.domain.Tuser;
import cn.sala.user.repository.TuserRepository;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/demo")
public class TuserController {

    private static final Logger logger = LoggerFactory.getLogger(TuserController.class);

    @Autowired
    private TuserRepository userRepository;

    @RequestMapping(value = "/test/{recordId}", method = RequestMethod.GET)
    @ResponseBody
    public void test(@PathVariable("recordId") String recordId) {
        // 测试分布式锁
        RLock lock = RedissLockUtil.lock(recordId);
        try {
            boolean res = lock.tryLock(3, 10, TimeUnit.SECONDS);
            if (res) {
                logger.info("进入业务代码: " + recordId);
                Pageable pageable = new PageRequest(0, 10, new Sort("name", "createDate"));
                Page<Tuser> userP = userRepository.findAll(pageable);
                System.out.println("pageSize..." + userP.getSize());
                System.out.println("list..." + userP.getContent().toString());
                System.out.println("totalPage..." + userP.getTotalPages());
                System.out.println("totalSum..." + userP.getContent().size());
                System.out.println("test lock print...");
                if (userP.getContent() != null) {
                    for (int i = 0; i < userP.getContent().size(); i++) {
                        Tuser tuser = userP.getContent().get(i);
                        System.out.println(tuser.toString());
                    }
                }
            }
            lock.unlock();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}
